import yaml
from typing import Any, Dict, Text, Union, Optional
from tools.get_path import get_absolute_path


def load_all_yaml_data(file_path: str) -> Dict:
    """加载整个YAML文件数据"""
    try:
        with open(get_absolute_path(file_path), 'r', encoding='utf-8') as file:
            return yaml.safe_load(file) or {}
    except Exception as e:
        raise ValueError(f"加载YAML文件失败: {str(e)}")


def get_case_data(file_path: str, case_name: str) -> Dict:
    """获取指定测试用例的数据"""
    all_data = load_all_yaml_data(file_path)
    return all_data.get('cases', {}).get(case_name, {})


def get_page_locators(file_path: str, page_name: str) -> Dict:
    """获取指定页面的定位器"""
    all_data = load_all_yaml_data(file_path)
    return all_data.get('locators', {}).get(page_name, {})


def load_yaml_data(file_path: str, **position_prams) -> Dict:
    try:
        # 这里可以直接使用上面的函数处理路径
        with open(get_absolute_path(file_path), 'r', encoding='utf-8') as file:
            yaml_data = yaml.safe_load(file)
    except yaml.YAMLError as e:
        raise Exception(f"YAML文件解析错误: {e}")
    except FileNotFoundError:
        raise Exception(f"文件不存在: {get_absolute_path(file_path)}")

    get_yaml_data: Dict = {}

    for key_name, path_list in position_prams.items():
        current_data = yaml_data
        for path in path_list:
            if isinstance(current_data, Dict) and path in current_data:
                current_data = current_data[path]
            else:
                current_data: Optional[Dict] = None
                print(f"数据为空: {current_data}")
                break
        get_yaml_data[key_name] = current_data
    return get_yaml_data
